package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportMethodBinding
import com.rzico.sbl.model.ManagerOrderData
import com.rzico.sbl.model.ManagerWayModel
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportMethodViewModel
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common_ui.base.BaseRootActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.slimadapter.SlimAdapter

class ReportMethodActivity : BaseRootActivity() {

    private lateinit var mBinding: ActivityReportMethodBinding

    private var mChartModel: ManagerWayModel? = null
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()
    private var mPayStarus = ""

    override fun getViewModel() = get<ReportMethodViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityReportMethodBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        transparentStatusBar()

        initData()
        initLayout()
        initTabLayout()

        getPayRange()
    }

    override fun initData() {
        mBinding.also {
            it.methodWay.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (
                        mChartModel == null
                        || value.toInt() !in mChartModel!!.weixinPay.indices
                    ) ""
                    else
                        mChartModel!!.weixinPay[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.methodWayTime.addTimeListener { start, end, _ ->
                mBeginDate = start
                mEndDate = end

                getViewModel().cancelRequest()
                getPayRange()
                updateList()
            }
        }
    }

    private fun initLayout() {
        mBinding.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关支付信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<ManagerOrderData>(R.layout.item_report_barrel) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_barrel_type)
                            gone(R.id.item_barrel_num_ll)
                            gone(R.id.item_barrel_divider)
                            text(R.id.item_barrel_title, bean.ename)
                            text(R.id.item_barrel_sn, bean.sn)
                            text(R.id.item_barrel_time, bean.createDate.getTimeString())
                            text(R.id.item_barrel_name_hint, "金额")
                            text(R.id.item_barrel_name, bean.amount.formatDecimal())
                            text(R.id.item_barrel_shop_hint, "司机")
                            text(R.id.item_barrel_shop, bean.name)

                            clicked {
                                goToOrderDetail("orderSn" to bean.sn)
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    /**
     * TabLayout 初始化
     */
    private fun initTabLayout() {
        mBinding
            .methodTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mPayStarus = when (it.position) {
                                0 -> "weixinPay"
                                1 -> "aliPay"
                                2 -> "cashPay"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(this.newTab().setText("微信"), true)
                addTab(this.newTab().setText("支付宝"), false)
                addTab(this.newTab().setText("现金"), false)
            }
    }

    /**
     * 设置柱状图数据
     */
    private fun setPayChart() {
        mBinding
            .methodWay
            .apply {
                if (mChartModel != null && (
                            !mChartModel?.weixinPay.isNullOrEmpty()
                                    || !mChartModel?.aliPay.isNullOrEmpty()
                                    || !mChartModel?.cashPay.isNullOrEmpty()
                            )
                ) {
                    setGroupData(
                        entries = arrayListOf(
                            mChartModel!!.weixinPay.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            },
                            mChartModel!!.aliPay.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            },
                            mChartModel!!.cashPay.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().methodColor(),
                        labelList = listOf("微信", "支付宝", "现金"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                } else clear()

                animateY(500)
            }
    }

    /**
     * 获取柱状图数据
     */
    private fun getPayRange() {
        getViewModel()
            .payRangeList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { data ->
                    mChartModel = data

                    setPayChart()
                }
            )
    }

    /**
     * 支付明细列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .payDetailList(
                page = index,
                type = mPayStarus,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .swipeRefresh
                        .isRefreshing = false
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .swipeRefresh
            .isRefreshing = true

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}